package vikaa.tools;


import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import vikaa.ui.Welcome;
import vikaa.wowo.cache.AuthoSharePreference;


import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class HttpUtil
{
	public static final int NETTYPE_WIFI = 0x01;
	public static final int NETTYPE_CMWAP = 0x02;
	public static final int NETTYPE_CMNET = 0x03;
	public static String PHPSESSID;
	public static final String HTTP_URL = 	"http://365wowo.sinaapp.com";
	public static final String BASE_URL = 	"http://365wowo.sinaapp.com/api/";
	public static final String WEIBO = 	"http://weibo.com/";
	
	
	/**
	 * 检测网络是否可用
	 * @return
	 */
	public static boolean isNetworkConnected() {
		ConnectivityManager cm = (ConnectivityManager) Welcome.wl.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = cm.getActiveNetworkInfo();
		return ni != null && ni.isConnectedOrConnecting();
	}
	
	/**
	 * @return NetworkType  0:No Network 1:WIFI 2:CMWAP 3:CMNET
	 */
	public int getNetworkType() {
		int networkType = 0;
		ConnectivityManager cm = (ConnectivityManager) Welcome.wl.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = cm.getActiveNetworkInfo();
		if (ni == null){
			return networkType;
		}
		networkType = ni.getType();
		if (networkType == ConnectivityManager.TYPE_MOBILE) {
			String type = ni.getExtraInfo();
			if (!StringUtils.isEmpty(type)) {
				if (type.toLowerCase().equals("cmnet"))
					networkType = NETTYPE_CMNET;
				else
					networkType = NETTYPE_CMWAP;
			}
		} else if (networkType == ConnectivityManager.TYPE_WIFI) {
			networkType = NETTYPE_WIFI;
		}
		return networkType;
	}
	
	public static String getRequest(String url)
		throws Exception
	{	HttpClient httpClient = new DefaultHttpClient();
		HttpGet get = new HttpGet(url);
		get.setHeader("Cookie", "PHPSESSID=" + AuthoSharePreference.getCookie(Welcome.wl));
		HttpResponse httpResponse = httpClient.execute(get);
		if (httpResponse.getStatusLine()
			.getStatusCode() == 200)
		{
			String result = EntityUtils
				.toString(httpResponse.getEntity());
			return result;
		}
		return null;
	}

	public static String postRequest(String url
		, Map<String ,String> rawParams)
	{	
		if(!isNetworkConnected()){
			String error =  "{\"result\":\"2\",\"info\":{\"error\":\""+"网络没有连接"+"\"}}";
			return error;
		}
		HttpPost post =null;
		HttpResponse httpResponse = null;
		DefaultHttpClient httpClient = new DefaultHttpClient();
		try{
			post = new HttpPost(url);
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			for(String key : rawParams.keySet())
			{
				params.add(new BasicNameValuePair(key , rawParams.get(key)));
			}
			httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 15000);
			httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 150000);
			post.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
			post.setHeader("Cookie", "PHPSESSID=" + AuthoSharePreference.getCookie(Welcome.wl));
			httpResponse = httpClient.execute(post);
			if (httpResponse.getStatusLine()
				.getStatusCode() == 200)
			{
				String result = EntityUtils.toString(httpResponse.getEntity());
				/*CookieStore mCookieStore =  httpClient.getCookieStore();
				List<Cookie>  cookies =  mCookieStore.getCookies();
				if (! cookies.isEmpty()){  
					for (Cookie cookie : cookies){  
						PHPSESSID = cookie.toString();
						Logger.i(PHPSESSID);
		        	}
		        } */
				try{
					new JSONObject(result);
				}catch(JSONException e){
					Logger.i(result);
				}
				return result;
				
			}
		}catch(Exception e){
			e.printStackTrace();
			Logger.i(e.getMessage());
			String error =  "{\"result\":\"2\",\"info\":{\"error\":\""+e.getMessage()+"\"}}";
			return error;
		}finally {  
            httpClient.getConnectionManager().shutdown();  
        }
		return null;
	}

	public static String postFileRequest(String url,Map<String,String> rawParams, String path) throws ClientProtocolException, IOException{
			HttpClient httpClient = new DefaultHttpClient();
		 	MultipartEntity mpEntity = new MultipartEntity();  
	        if (rawParams != null && !rawParams.isEmpty()) {  
	            for (Map.Entry<String, String> entry : rawParams.entrySet()) {  
	                StringBody par = new StringBody(entry.getValue());  
	                mpEntity.addPart(entry.getKey(), par);  
	            }  
	        }  
	        if(!path.equals("")){
	            FileBody file = new FileBody(new File(path));  
	            mpEntity.addPart("Filedata", file);  
	        }
	        HttpPost post = new HttpPost(url);  
	        post.setEntity(mpEntity);  
	        //post.setHeader("Cookie", "PHPSESSID=" + AuthoSharePreference.getCookie(Welcome.wl));
	        //httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 15000);
			//httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 15000);
	        HttpResponse httpResponse = httpClient.execute(post);
	        if (httpResponse.getStatusLine().getStatusCode() == 200)
	    		{
	    			String result = EntityUtils
	    				.toString(httpResponse.getEntity());
	    			return result;
	    		}
	        httpClient.getConnectionManager().shutdown();
		return null;
	}
	
	public static String HttpUrlComplete(String url){
        if(url.indexOf("http") != -1){
        	return url;
        }else{
        	return (HttpUtil.HTTP_URL + url);
        }
	}
}
